﻿@using IotClientApp.Shared
@using IotClientApp.Shared.Enums;
@using Newtonsoft.Json;
@inject HttpClient httpClient
@inject ISnackbar Snackbar

<MudDialog>
    <TitleContent>
        <MudText Typo="Typo.h6">
            <MudIcon Icon="@Icons.Material.Filled.ControlPoint" Class="mr-3 mb-n1" />
            下控
        </MudText>
    </TitleContent>
    <DialogContent>
        <MudTextField @bind-Value="value" Label="值" />
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel">取消</MudButton>
        <MudButton Color="Color.Success" OnClick="SaveServer">确定</MudButton>
    </DialogActions>
</MudDialog>
@code {
    [CascadingParameter] MudDialogInstance MudDialog { get; set; }

    [Parameter] 
    public string deviceId { get; set; }
    /// <summary>
    /// 标题
    /// </summary>
    [Parameter]
    public int pointId { get; set; }
    private string value { get; set; }

    private void Cancel()
    {
        MudDialog.Cancel();
    }
    private void onchange()
    {
        Console.WriteLine();
    }
    private async Task SaveServer()
    {
        Console.WriteLine($"下控值{value}");
        var response = await httpClient.PostAsJsonAsync("api/Device/ControlPoint", new ControlPointModel
            {
                DeviceId = deviceId,
                PointId = pointId,
                Value = value
            });
        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();
            try
            {
                var result = JsonConvert.DeserializeObject<ApiResult<DeviceInfoModel>>(responseContent);
                if (result != null)
                {
                    if (result.Code == ResultCode.Success)
                    {
                        //In a real world scenario this bool would probably be a service to delete the item from api/database
                        Snackbar.Add("下控", Severity.Success);
                        MudDialog.Close(DialogResult.Ok("ok"));
                    }
                    else
                    {
                        Snackbar.Add(result.ErrorMsg, Severity.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        else
        {
            Snackbar.Add("下控", Severity.Error);
        }
    }
}